import axios from 'axios';
import {
  showFullScreenLoading,
  tryHideFullScreenLoading,
} from './requsetLoading';
import vue from 'vue';
import { Notify, Dialog } from 'vant';
import { getPhoneNum } from '@/utils/public';
import { getCookie,delCookie } from '@/utils/myCookie';
vue.use(Notify);

function creatService(needToken, showLoading) {
  const service = axios.create({
    baseURL: VUE_APP_HNNXS_BASE_URL, // api 的 base_url
    withCredentials: true, // 跨域设置
    timeout: 60000, // 请求超时时间
  });
  var channel = getPhoneNum();
  let myToken = sessionStorage.getItem('mtoken');
  if (myToken != 'true' && channel != '102') {
    Dialog.alert({
      title: '温馨提示',
      message: '当前访问异常，请退出重新访问',
    }).then(() => {
      var userAgent = navigator.userAgent.toLowerCase();
      if (
        userAgent.match(/android_hnrcc/i) == 'android_hnrcc' ||
        userAgent.match(/ios_hnrcc/i) == 'ios_hnrcc'
      ) {
        NXYJS.goHomePage(); // eslint-disable-line
      } else {
        WeixinJSBridge.call('closeWindow'); // eslint-disable-line
      }
      return;
    });
  }

  //请求前拦截器
  service.interceptors.request.use(
    (config) => {
      // 请求前需要设置header之类在此设置
      if (showLoading) {
        showFullScreenLoading();
      }
      config.headers['X-Requested-With'] = 'XMLHttpRequest';
      config.headers['Content-Type'] = 'application/json;charset=UTF-8';
      config.headers['infoq'] = 'channelId=' + channel;
      config.headers['duplicationId'] = Math.random();
      const isToken = (config.headers || {}).isToken === false;
      const token = getCookie('ttkn2');
      if (needToken) {
        if (token && !isToken) {
          config.headers['Authorization'] = 'Bearer ' + token; // 让每个请求携带自定义token 请根据实际情况自行修改
        }
      }
      return config;
    },
    (error) => {
      if (service.showLoading) {
        tryHideFullScreenLoading();
      }
      return Promise.reject(error);
    }
  );

  // response拦截器
  service.interceptors.response.use(
    (response) => {
      let res = response.data;
      // 可做返回状态拦截处理
      if (showLoading) {
        tryHideFullScreenLoading();
      }
      if (res.code == '401') {
        Dialog.alert({
          title: '温馨提示',
          message: '登录状态已过期，请退出重新登录',
        }).then(confirm=>{
          delCookie('ttkn2');
          window.sessionStorage.clear();
          window.location.replace(window.location.origin);
        })
        return;
      }
      return res;
    },
    (error) => {
      if (showLoading) {
        tryHideFullScreenLoading();
      }
      //错误处理
      if (error && error.response) {
        switch (error.response.status) {
          case 400:
            error.message = '请求错误';
            break;
          case 403:
            error.message = '拒绝访问';
            break;
          case 404:
            error.message = `请求地址出错: ${error.response.config.url}`;
            break;
          case 408:
            error.message = '请求超时';
            break;
          case 500:
            error.message = '服务器内部错误';
            break;
          case 501:
            error.message = '服务未实现';
            break;
          case 502:
            error.message = '网关错误';
            break;
          case 503:
            error.message = '服务不可用';
            break;
          case 504:
            error.message = '网关超时';
            break;
          default:
        }
      } else {
        error.message = '请求无响应，请检查您的网络';
      }
      Notify(error.message);
      return Promise.reject(error.response.data);
    }
  );
  return service;
}
// 不要token
export const service = creatService(false, true);

// 不要token,不要loading
export const service2 = creatService(false, false);

// 需要token
export const request = creatService(true, true);

//要token,不要loading
export const request2 = creatService(true, false);
